package com.luoke.dao.impl;


import com.luoke.dao.UserDao;
import com.luoke.pojo.entity.User;
import com.luoke.util.myjdbc.QueryWrapper;
import com.luoke.util.myjdbc.SQLEnum;
import com.luoke.util.myjdbc.UpdateWrapper;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

public class UserDaoImpl implements UserDao {




    @Override
    public User getUserByNameAndPwd(String name, String pwd) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select(SQLEnum.ASTERISK_SIGN.getValue())
                .from(User.class)
                .where(User::getName,name)
                .and(User::getPassword,pwd);
         return this.selectOne(userQueryWrapper);
    }

    @Override
    public Long saveUser(User user) {
       return this.insert(user);
    }

    @Override
    public User getUserByName(String name) {
        QueryWrapper<User> getUserByNameQueryWrapper = new QueryWrapper<>();
        getUserByNameQueryWrapper.select(SQLEnum.ASTERISK_SIGN.getValue())
                .from(User.class)
                .where(User::getName,name);
        return this.selectOne(getUserByNameQueryWrapper);
    }

    @Override
    public void UpdateLastTimeByName(String username) {
        UpdateWrapper<User> updateLastTimeByNameWrapper = new UpdateWrapper<>();
        updateLastTimeByNameWrapper.update(User.class)
                .set(User::getLastLogin, LocalDateTime.now().toString())
                .where(User::getName,username);
        this.update(updateLastTimeByNameWrapper);
    }

    @Override
    public List<String> getOnlinePlayers() {

        QueryWrapper<User> getOnlinePlayersqueryWrapper = new QueryWrapper<>();
        getOnlinePlayersqueryWrapper.select(SQLEnum.ASTERISK_SIGN.getValue())
                .from(User.class)
                .where(User::getOnline,"1");
        List<User> users = this.selectAll(getOnlinePlayersqueryWrapper);
        System.out.println(users.stream().map(User::getName).collect(Collectors.toList()));
        return users.stream().map(User::getName).collect(Collectors.toList());
//
//
//        String sql = "SELECT name FROM user WHERE online = 1";
//        try {
//            return DatabaseUtil.selectAll(sql, String.class);
//        } catch (SQLException | ReflectiveOperationException e) {
//            throw new RuntimeException("查询在线玩家失败", e);
//        }
//        return Collections.emptyList(); //返回空集合
    }

    @Override
    public void updateOnlineStatus(String username, boolean isOnline) {
        UpdateWrapper<User> updateOnlineStatus = new UpdateWrapper<>();
        updateOnlineStatus.update(User.class)
                .set(User::getOnline, isOnline ? "1" : "0")
                .where(User::getName, username);
        this.update(updateOnlineStatus);
    }


}
